import React, { useState, useRef, useEffect } from 'react';
import Draggable from 'react-draggable';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import styled from '@emotion/styled';
import { Form, Modal, Button } from 'antd';
import AgentService, { IEvent } from '@/modules/Agent';
import { getSessionBizSummary, confirmSessionBizSummary } from '@/api';
import Message from '@/utils/message';
import { useTranslation } from 'react-i18next';

import SummaryInput from '@/components/SessionSummary/SummaryInput';
import SummaryTextarea from '@/components/SessionSummary/SummaryTextarea';
import SummaryCheckbox from '@/components/SessionSummary/SummaryCheckbox';
import SummarySelect from '@/components/SessionSummary/SummarySelect';
import SummaryRadio from '@/components/SessionSummary/SummaryRadio';
import AfterworkTime from '@/components/SessionSummary/AfterworkTime';

const TitleP = styled.p`
	text-align: center;
	width: 100%;
`;

interface SummaryFormProps {
	type?: string; // '' | edit | confirm | view
	sessionId?: string;
	sceneId?: string;
	onClose: () => void;
	onSave?: () => void;
	isNotice?: boolean;
}

const SummaryForm = (props: SummaryFormProps) => {
	const { t } = useTranslation();
	const { onClose, type = 'confirm', sessionId, sceneId, onSave, isNotice = true } = props;
	const [form] = Form.useForm();

	const [summaryList, setSummaryList] = useState([]);
	const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
	const draggleRef = useRef<HTMLDivElement>(null);

	useEffect(() => {
		const handleSummaryMessage = (message: any) => {
			console.log('handleSummaryMessage', message);
			// {"bizSummaryId": 1, "name": "", "type": "textarea", "data": {}, "value": {}, "isRequired": "Y"}
			const { bizSummaryId, value, type } = message.data.data.data;
			const from = message.data.data.from;
			if (from === AgentService.user?.clientId || from === AgentService.clientID) {
				return;
			}
			form.setFieldsValue({ [type + bizSummaryId]: value });
		};
		// addListener
		AgentService.addListener(IEvent.ON_SYNC_SESSION_SUMMARY, handleSummaryMessage);

		if (type === 'view' || type === 'edit') {
			// 获取会话小结内容
			getSummaryValueById(sessionId || '');
		} else {
			const list = AgentService.getSummaryList() || [];
			setSummaryList(list);
			// 获取会话小结内容
			getSummaryValue();
		}

		return () => {
			// removeListener
			AgentService.removeListener(IEvent.ON_SYNC_SESSION_SUMMARY, handleSummaryMessage);
		};
	}, []);

	const getSummaryValue = async () => {
		getSessionBizSummary(AgentService.sessionId || AgentService.lastSessionId)
			.then(res => {
				const { code, data } = res.data;
				if (code === 200) {
					// update ui
					for (let i = 0; i < data.length; i++) {
						const item = data[i];
						const { bizSummaryId, type, value } = item;
						form.setFieldsValue({ [type + bizSummaryId]: value });
					}
				}
			})
			.catch(error => {
				console.log('getSummaryList error', error);
				Message.warning(t('failed-get-session-summary'));
			});
	};

	const getSummaryValueById = async (sessionId: string) => {
		getSessionBizSummary(sessionId)
			.then(res => {
				const { code, data } = res.data;
				if (code === 200) {
					// update ui
					const list = data.map((item: any) => {
						return {
							id: item.bizSummaryId,
							type: item.type,
							name: item.name,
							data: item.data,
							isRequired: item.isRequired,
							value: item.value || ''
						};
					});
					setSummaryList(list);
					setTimeout(() => {
						// update ui
						for (let i = 0; i < list.length; i++) {
							const item = list[i];
							const { id, type, value } = item;
							form.setFieldsValue({ [type + id]: value });
						}
					}, 50);
				}
			})
			.catch(error => {
				console.log('getSummaryList error', error);
				Message.warning(t('failed-get-session-summary'));
			});
	};

	const confirmSummary = async (data: any) => {
		confirmSessionBizSummary(sessionId || AgentService.sessionId || AgentService.lastSessionId, data)
			.then(res => {
				console.log('confirmSessionBizSummary', res.data);
				const { code } = res.data;
				if (code === 200) {
					if (type === 'edit') {
						Message.success(t('save-success'));
					} else if (type === 'confirm') {
						Message.success(t('session-summary-confirmed-success'));
					}
				}
			})
			.catch(error => {
				console.log('confirmSummary error', error);
				if (type === 'edit') {
					Message.warning(t('save-failed'));
				} else if (type === 'confirm') {
					Message.warning(t('session-summary-confirmed-failed'));
				}
			});
	};

	const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
		const { clientWidth, clientHeight } = window.document.documentElement;
		const targetRect = draggleRef.current?.getBoundingClientRect();
		if (!targetRect) {
			return;
		}
		setBounds({
			left: -targetRect.left + uiData.x,
			right: clientWidth - (targetRect.right - uiData.x),
			top: -targetRect.top + uiData.y,
			bottom: clientHeight - (targetRect.bottom - uiData.y)
		});
	};
	const handleOk = async () => {
		try {
			const values = await form.validateFields();
			console.log('Success:', values);
			// submit summary
			const list = summaryList.map((item, idx) => {
				const { id, type, name, isRequired, data } = item;
				return {
					bizSummaryId: id,
					name: name,
					type: type,
					data: data,
					value: values[type + id],
					isRequired: isRequired,
					index: idx
				};
			});
			await confirmSummary({ scenId: sceneId, bizSummary: list });
			onSave && onSave();
		} catch (errorInfo) {
			console.log('Failed:', errorInfo);
		}
	};

	const handleConfirm = async () => {
		try {
			const values = await form.getFieldsValue(true);
			// { scenId, bizSummary: [{bizSummaryId, name, type, data, isRequired, value }] }
			const list = summaryList.map((item, idx) => {
				const { id, type, name, isRequired, data } = item;
				return {
					bizSummaryId: id,
					name: name,
					type: type,
					data: data,
					value: values[type + id],
					isRequired: isRequired,
					index: idx
				};
			});
			await confirmSummary({ scenId: AgentService.lastSceneId, bizSummary: list });
			onClose();
		} catch (errorInfo) {
			console.log('Failed:', errorInfo);
		}
	};

	const handleCancel = () => {
		onClose();
	};

	const handleChange = async (idx: number, value: any, item: any) => {
		if (!AgentService.sessionId) {
			return;
		}
		if (!isNotice) {
			return;
		}
		console.log('idx = ', idx, 'value = ', value, 'type = ', item.type);
		// send sync request to server
		try {
			let data = {
				bizSummaryId: item.id,
				name: item.name,
				type: item.type,
				data: item.data,
				value: value,
				isRequired: item.isRequired,
				index: idx
			};
			const resp = await AgentService.syncSessionSummary(data, 'agents'!);
			console.log('syncSessionSummary success', resp);
		} catch (error) {
			console.log('syncSessionSummary error', error);
		}
	};

	const FormContent = () => {
		return (
			<Form form={form} name="basic" style={{ maxWidth: 600 }} initialValues={{ remember: true }} autoComplete="off" layout="vertical" disabled={type === 'view'}>
				{summaryList.map((item, idx) => {
					const { id, type, name, isRequired, data = {} } = item;
					const { options = [] } = data as any;

					switch (type) {
						case 'input':
							return <SummaryInput key={idx} label={name} name={'input' + id} required={isRequired === 'Y'} onBlur={value => handleChange(idx, value, item)} />;
						case 'checkbox':
							return (
								<SummaryCheckbox
									key={idx}
									label={name}
									name={'checkbox' + id}
									required={isRequired === 'Y'}
									options={options || []}
									onChange={value => handleChange(idx, value, item)}
								/>
							);
						case 'radio':
							return <SummaryRadio key={idx} label={name} name={'radio' + id} required={isRequired === 'Y'} options={options || []} onChange={value => handleChange(idx, value, item)} />;
						case 'select':
							return (
								<SummarySelect key={idx} label={name} name={'select' + id} required={isRequired === 'Y'} options={options || []} onChange={value => handleChange(idx, value, item)} />
							);
						case 'textarea':
							return <SummaryTextarea key={idx} label={name} name={'textarea' + id} required={isRequired === 'Y'} onBlur={value => handleChange(idx, value, item)} />;
						default:
							return null;
					}
				})}
			</Form>
		);
	};

	const FooterItem =
		type === 'edit' ? (
			<>
				<Button onClick={handleCancel}>{t('cancel')}</Button>
				<Button type="primary" onClick={handleOk}>
					{t('sure')}
				</Button>
			</>
		) : type === 'confirm' ? (
			<>
				<AfterworkTime onConfirm={handleConfirm} />
			</>
		) : null;

	return (
		<Modal
			open={true}
			title={t('session-summary')}
			maskClosable={false}
			mask={false}
			zIndex={99}
			width={600}
			bodyStyle={{ height: '500px', overflow: 'auto' }}
			footer={FooterItem}
			closable={!type || type === 'view'}
			onOk={handleOk}
			onCancel={handleCancel}
			modalRender={node => (
				<Draggable handle=".ant-modal-header" bounds={bounds} onStart={(event, uiData) => onStart(event, uiData)}>
					<div ref={draggleRef}>{node}</div>
				</Draggable>
			)}
		>
			<FormContent />
		</Modal>
	);
};

export default SummaryForm;
